﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows.Media.Imaging;

namespace Moonwish.Silverlight.OsAvatar.Programs
{
    /// <summary>
    /// 程序数据集合,由外部菜单创建。
    /// write by zhlin 2012-02-25
    /// </summary>
    public class ProgramCollection : KeyedCollection<string, ProgramWrapper>, INotifyCollectionChanged
    {
        private ProgramWrapper _parent;

        public ProgramCollection(ProgramWrapper parent)
        {
            _parent = parent;
        }

        public new void Add(ProgramWrapper item)
        {
            base.Add(item);

            item.Parent = Parent;

            if (Parent != null)
            {
                var icon32 = (BitmapImage)Parent.Icon32;
                if (icon32.UriSource.OriginalString.IndexOf("app64.png", StringComparison.Ordinal) != -1)
                {
                    Parent.Icon32 = new BitmapImage(new Uri("/Moonwish.Silverlight.OsAvatar;component/Icons/folder64.png", UriKind.Relative));
                }
            }

            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, this, 0));
            }
        }

        public new void Remove(ProgramWrapper item)
        {
            base.Remove(item);

            if (Parent != null && Parent.Children.Count == 0)
            {
                var icon32 = (BitmapImage)Parent.Icon32;
                if (icon32.UriSource.OriginalString.IndexOf("folder64.png", StringComparison.Ordinal) != -1)
                {
                    Parent.Icon32 = new BitmapImage(new Uri("/Moonwish.Silverlight.OsAvatar;component/Icons/app64.png", UriKind.Relative));
                }
            }

            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, this, 0));
            }
        }

        public ProgramWrapper Parent
        {
            get { return _parent; }
        }

        protected override string GetKeyForItem(ProgramWrapper item)
        {
            return item.Id;
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged;
    }
}
